package cn.edu.csust.cvs.management.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
/**
 * @Auther: snail
 * @Date: 2021/2/25 00:30
 * @Description: 文件操作工具类
 */
@Slf4j
public class FileOptUtils {

    /**
     * 创建系统目录，格式yyyyMMdd
     * @param path
     * @return
     */
    public static File createFileBySysDate(String path) {

        // 1. 读取系统时间
        Calendar calendar = Calendar.getInstance();
        Date time = calendar.getTime();

        // 2. 格式化系统时间
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String fileName = format.format(time);

        // 3. 创建文件夹
        String newPath = path + fileName;
        File file = new File(newPath);
        //如果文件目录不存在则创建目录
        if (!file.exists()) {
            if (!file.mkdir()) {
                return null;
            }
        }
        return file;
    }

    /**
     * 创建合并文件
     * @param path
     * @param data
     * @return
     * @throws IOException
     */
    public static File createMergeFile(String path, String data) throws IOException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        // 1. 创建文件
        String newPath = path + "filelist_" + LocalDateTime.now().format(formatter) + ".txt";
        File file = new File(newPath);
        //如果文件目录不存在则创建
        if (!file.exists()) {
            if (!file.createNewFile()) {
                log.error("当前路径不存在，创建失败");
                return null;
            }
        }
        // 2. 数据写入
        try {
            FileWriter fw = new FileWriter(file, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(data);
            bw.flush();
            bw.close();
            fw.close();
        }catch (IOException e){
            return null;
        }
        return file;
    }

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String newPath = "E:\\Work" + "\\filelist_" + LocalDateTime.now().format(formatter) + ".txt";
        System.out.println(newPath);
    }
}
